﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using amis6_api.Common;
using amis6_api.Dto;
using amis6_api.Model;
using amis6_api.Utils;
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace amis6_api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public LoginController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 用户登录接口
        /// </summary>
        /// <remarks>
        /// 请求参数:
        /// {"name": "admin","passwd": "202CB962AC59075B964B07152D234B70"}
        /// </remarks>
        /// <param name="userLoginDto">用户登录参数</param>
        /// <returns></returns>
        [HttpPost("login")]
        public BaseResult<LoginRespDto> UserLogin([FromBody]UserLoginDto userLoginDto)
        {
            using var conn = DbFactory.Db();
            var user = conn.QueryFirstOrDefault<User>("select * from t_Users where U_Name=@username and U_PWD=@passwd and U_Enabled='True'", new { username = userLoginDto.Name, passwd = userLoginDto.Passwd });
            LoginRespDto loginRespDto = new LoginRespDto();

            if (user == null)
            {
                return BaseResult<LoginRespDto>.Error("用户名密码错误!");
            }
            else
            {
                Dictionary<string, object> payLoad = new Dictionary<string, object>
                {
                    //payLoad.Add("sub", "rober");
                    { "jti", user.U_ID },
                    { "iss", _configuration["Jwt:Issuer"] },
                    { "aud", _configuration["Jwt:Audience"] }
                };
                string token = JwtUtils.CreateTokenByHandler(payLoad, Convert.ToInt32(_configuration["Jwt:ExpireMinutes"]));
                conn.Execute("update t_Users set U_Token=@token where U_ID=@uid ", new { token = token, uid = user.U_ID });
                loginRespDto.Token = token;
            }

            return BaseResult<LoginRespDto>.OK(loginRespDto);
        }
    }
}